package com.cskaoyan.order.rocketmqconfig;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ProcessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;


/**
 * @ClassName OrderDelayMsgProducer
 * @Description TODO
 * @Author XiaoWJ
 * @Date 2022/9/22 14:45
 **/

@Slf4j
@Component
public class OrderDelayMsgProducer {

    @Autowired
    DefaultMQProducer defaultMQProducer;

    @Autowired
    OrderDelayMsgProperties msgProperties;

    @Autowired
    OrderDelayCancelProducerProperties properties;


    public boolean sendOrderCancelMsg(String orderId) {

        // 创建消息对象
        Message message = new Message();

        // 设置消息的主题
        message.setTopic(msgProperties.getTopic());

        // 设置消息的内容
        message.setBody(orderId.getBytes(Charset.forName(msgProperties.getCharset())));

        // 设置消息的延迟级别
        message.setDelayTimeLevel(msgProperties.getDelayLevel());

        // 发送消息
        Exception ex = null;

        SendResult sendResult = null;
        try {
            sendResult = defaultMQProducer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
            ex = e;
        } catch (RemotingException e) {
            e.printStackTrace();
            ex = e;
        } catch (MQBrokerException e) {
            e.printStackTrace();
            ex = e;
        } catch (InterruptedException e) {
            e.printStackTrace();
            ex = e;
        }

        // 出现异常，发送消息失败
        if (ex != null) {
            log.info("订单：" + orderId + "超时自动取消信息发送出现异常，发送失败");
            return false;
        }

        if (sendResult != null && SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
            //消息发送成功
            log.info("订单：" + orderId + "超时自动取消信息已发送");
            return true;
        }

        return false;

    }
}